// store/modules/user.js
import { login, getUserInfo } from "@/api/user.js"
const user = {
  state: {
    token: uni.getStorageSync('token') || '',
    userInfo: null
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      uni.setStorageSync('token', token)
    },
    clearToken(state) {
      state.token = ''
      state.userInfo = null
      uni.removeStorageSync('token')
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    async login({ commit }, { mobile, password }) {
      try {
        // 调用登录API
        const response = await login({ mobile, password })
        const token = response.data.token
        commit('setToken', token)
        // 登录成功后可以获取用户信息
        const userInfoResponse = await getUserInfo()
        commit('setUserInfo', userInfoResponse.data)
        return token
      } catch (error) {
		  console.log(error)
        console.log(error.message)
        // 处理登录错误
        throw new Error(error?.message || '登录失败')
      }
    },
    logout({ commit }) {
      commit('clearToken')
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    userInfo: state => state.userInfo
  }
}

export default user